<!--
 * @Author: fisher
 * @Date: 2024-02-23 20:57:36
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-11-01 11:05:35
 * @FilePath: \allfront\src\modules\cloud\instance\index.vue
 * @Description: 
-->
<template>
  <div class="moduleMain" v-loading="loading" element-loading-text="Loading...">
    <div class="operate">
      <el-input
        v-model="search"
        placeholder="请输入实例名称"
        class="input-with-select"
      >
        <template #append>
          <el-button :icon="Search" @click="searchInstance" />
        </template>
      </el-input>
      <el-button type="success" @click="startInstance" style="margin-left: auto"
        >启动实例</el-button
      >
      <el-button type="info" @click="stopInstance">停止实例</el-button>
      <el-button type="primary" @click="addInstance">新增实例</el-button>
      <!-- <el-button type="warning" @click="editInstance">修改实例</el-button> -->
      <el-button type="danger" @click="deleteInstance">删除实例</el-button>
    </div>
    <div class="table">
      <el-table
        stripe
        :data="tableData"
        style="width: 100%; height: calc(100% - 60px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column property="clusterHost" label="集群节点" width="120" />
        <el-table-column
          property="name"
          label="实例名称"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column property="port" label="实例端口" width="120" />
        <!-- <el-table-column property="projectId" label="ue工程id" width="300" /> -->
        <el-table-column
          property="projectName"
          label="ue工程名称"
          width="180"
          show-overflow-tooltip
        />

        <el-table-column property="runStatus" label="运行状态" width="120">
          <template #default="scope">
            <el-button type="info" v-show="!scope.row.runStatus">
              未启动
            </el-button>
            <el-button
              style="margin-left: 0"
              type="success"
              v-show="scope.row.runStatus"
            >
              运行中
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="实例运行时长" width="140" show-overflow-tooltip>
          <template #default="scope">
            <span>
              {{
                scope.row.runTimestamp !== 0
                  ? formatSeconds(
                      Math.ceil(
                        (scope.row.totalRuntimes +
                          Date.now() -
                          scope.row.runTimestamp) /
                          1000,
                      ),
                    )
                  : formatSeconds(0)
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column property="connectStatus" label="连接状态" width="120">
          <template #default="scope">
            <el-button type="info" v-show="!scope.row.connectStatus">
              未连接
            </el-button>
            <el-button
              style="margin-left: 0"
              type="success"
              title="点击查看连接信息"
              v-show="scope.row.connectStatus"
            >
              已连接
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          property="createdAt"
          label="创建时间"
          show-overflow-tooltip
          width="120"
        >
          <template #default="scope">
            {{ dayjs(scope.row.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              v-show="!scope.row.runStatus"
              type="info"
              title="实例未启动"
            >
              测试
            </el-button>
            <el-button
              style="margin-left: 0"
              v-show="scope.row.runStatus"
              type="success"
              @click="testInstance(scope.row)"
            >
              测试
            </el-button>

            <el-button
              style="margin-left: 10px"
              v-show="!scope.row.runStatus"
              type="info"
              title="实例未启动"
            >
              踢人
            </el-button>
            <el-button
              style="margin-left: 10px"
              v-show="scope.row.runStatus"
              type="danger"
              @click="kickoff(scope.row)"
            >
              踢人
            </el-button>
            <!-- <el-button
              style="margin-left: 10px"
              v-show="!scope.row.runStatus"
              type="info"
              title="实例未启动"
            >
              复制
            </el-button> -->
            <el-button
              style="margin-left: 10px"
              type="primary"
              @click="copyInstance(scope.row)"
            >
              复制
            </el-button>
            <!-- <el-button type="primary" @click="instanceDetail(scope.row)">
              详情
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="table_page"
        :current-page="pageNo"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <InstanceDialog
      ref="instanceDialog"
      @updateList="updateList"
    ></InstanceDialog>
    <!-- <UeclientDialog
      ref="ueclientDialog"
      :ueclientData="ueclientData"
    ></UeclientDialog> -->
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue';
import { ref, reactive, onMounted, watch } from 'vue';
import InstanceDialog from './instanceDialog.vue';
// import UeclientDialog from './ueclientDialog.vue';
import dayjs from 'dayjs';
import { useAxios } from '@/hooks/useAxios';
import { useDeleteConfirmation } from '@/hooks/useDeleteConfirm';
import { storeToRefs } from 'pinia';
import { useUeinstance } from '@/store/ueinstance.js'; // 路径要指向你的 store 文件
import { formatSeconds, copyText } from '@/utils/index.js';
const { post, loading } = useAxios();
const { deleteData } = useDeleteConfirmation();
const search = ref('');
const instanceDialog = ref();

const searchInstance = () => {
  getData();
};
const addInstance = () => {
  instanceDialog.value.dialogFormVisible = true;
  instanceDialog.value.initForm();
};
// const copyForm = ref({});
const copyInstance = data => {
  // console.log('copyInstance', data);
  // copyForm.value = data;
  instanceDialog.value.dialogFormVisible = true;
  instanceDialog.value.initCopyForm(data);
};
const updateList = () => {
  getData();
};
// const editInstance = () => {};
/**
 * @description: 删除实例数据
 * @return {*}
 */
const deleteInstance = () => {
  deleteData(selectData, data => {
    return post('/ueinstance/deleteInstance', {
      ids: data,
    }).then(() => {
      selectData.length = 0;
      getData();
    });
  });
};
/**
 * @description: 启动实例
 * @return {*}
 */
const startInstance = () => {
  if (!selectData.length) {
    ElNotification({
      title: 'Info',
      message: '请先选择实例，在进行操作！',
      type: 'info',
    });
    return;
  }
  post('/ueinstance/startInstances', {
    ids: selectData,
  }).then(res => {
    if (res?.status) {
      selectData.length = 0;
      // 更新数据
      getData();
    }
  });
};
const stopInstance = () => {
  if (!selectData.length) {
    ElNotification({
      title: 'Info',
      message: '请先选择实例，在进行操作！',
      type: 'info',
    });
    return;
  }
  post('/ueinstance/stopInstances', {
    ids: selectData,
  }).then(res => {
    if (res?.status) {
      selectData.length = 0;
      // 更新数据
      getData();
    }
  });
};
/**
 * @description: 获取列表数据
 * @return {*}
 */
let tableData = reactive([]);
let selectData = reactive([]);
let total = ref(0);
let pageNo = ref(1);
let pageSize = ref(10);
onMounted(() => {
  getData();
});
const getData = () => {
  const data = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    search: search.value,
  };
  post('/ueinstance/getInstanceList', data).then(res => {
    if (res?.status) {
      // 先清空，后赋值,表格数据赋值
      tableData.length = 0;
      tableData.push(...res.data);
      total.value = res.page.total;
    }
  });
};
const handleSelectionChange = val => {
  if (val.length) {
    selectData.length = 0;
    val.forEach(item => {
      selectData.push(item.id);
    });
  }
};
const handleSizeChange = val => {
  pageSize.value = val;
  getData();
};
const handleCurrentChange = val => {
  pageNo.value = val;
  getData();
};

const ueinstanceStore = useUeinstance();
const { connectChange } = storeToRefs(ueinstanceStore);
watch(connectChange, val => {
  if (val) {
    getData();
    ueinstanceStore.updataconnectChange(false);
  }
});
// ue连接客户端弹窗
const ueclientDialog = ref();
const ueclientData = reactive({});
const showUeclientDialog = data => {
  ueclientDialog.value.dialogFormVisible = true;
  Object.assign(ueclientData, data);
  ueclientDialog.value.handleData();
};

/**
 * @description: 测试实例连接
 * @param {*} data
 * @return {*}
 */
const testInstance = data => {
  console.log('data', data);
  window.open(`/#/pixelstream/${data.id}`);
};

const copyStream = data => {
  let url = '';
  if (data.useHttps) {
    url = `wss://${data.instanceIp}:${data.port}`;
  } else {
    url = `ws://${data.instanceIp}:${data.port}`;
  }
  copyText(url);
};
const kickoff = data => {
  console.log('kickoff', data);
  if (!data.connectStatus) {
    ElNotification({
      title: '警告',
      message: '当前实例无用户连接！',
      type: 'warning',
    });
    return;
  }
  post('/ueinstance/closeClient', {
    instanceId: data.id,
    connectionId: data.connections[0].id,
  }).then(res => {
    if (res.status) {
      ElMessage({
        type: 'success',
        message: '关闭连接成功!',
      });
    }
  });
};
</script>
<style scoped>
.moduleMain {
  padding: 20px;
  box-sizing: border-box;
}

.operate {
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  /* justify-content: flex-end; */
}
.input-with-select {
  width: 200px;
  height: 38px;
}
.table {
  height: calc(100% - 100px);
}
/* :deep(.el-table) {
  height: calc(100% -60px);
} */
.table_page {
  height: 60px;
  justify-content: flex-end;
}
</style>
